package java8.optional;

import java8.support.Student;

import java.util.Optional;

public class OptionalUse {
    //错误的用法
    public static String getNameError(Student u) {
        Optional<Student> user = Optional.ofNullable(u);
        if (!user.isPresent())
            return "Unknown";
        return user.get().getName();
    }

    //正确的用法
    public static String getNameCorrect(Student u) {
        return Optional.ofNullable(u)
                .map(user -> u.getName())
                .orElse("Unknown");
    }

    //错误的链式获取
    public static String getChampionNameError(Competition comp) throws IllegalArgumentException {
        if (comp != null) {
            CompResult result = comp.getResult();
            if (result != null) {
                Student champion = result.getChampion();
                if (champion != null) {
                    return champion.getName();
                }
            }
        }
        throw new IllegalArgumentException("The value of param comp isn't available.");
    }

    //正确的链式获取
    public static String getChampionName(Competition comp) throws IllegalArgumentException {
        return Optional.ofNullable(comp)
                .map(c -> c.getResult())
                .map(r -> r.getChampion())
                .map(u -> u.getName())
                .orElseThrow(() -> new IllegalArgumentException("The value of param comp isn't available."));
    }

      //Optional可以用来检验参数的合法性
/*    public void setName(String name) throws IllegalArgumentException {
        this.name = Optional.ofNullable(name).filter(User::isNameValid)
                .orElseThrow(()->new IllegalArgumentException("Invalid username."));
    }*/


    class Competition {
        private CompResult result;

        public CompResult getResult() {
            return result;
        }
    }

    class CompResult {
        private Student champion;

        public Student getChampion() {
            return champion;
        }
    }
}
